import time
from django.shortcuts import render, HttpResponse, redirect
from web.forms.project import ProjectModelForm
from django.http import JsonResponse
from web import models
from utils.tencent.cos import create_bucket

def project_list(request):
    form = ProjectModelForm(request)
    project_dict = {
        'star': [],
        'my': [],
        'join': [],
    }
    # 当前用户创建的所有项目
    my_project_list = models.Project.objects.filter(creator=request.saas.user)
    for project in my_project_list:
        if project.star:
            project_dict['star'].append({'value': project, 'type': 'my'})
        else:
            project_dict['my'].append(project)
    # 当前用户参与的所有项目
    join_project_list = models.ProjectUser.objects.filter(user=request.saas.user)
    for item in join_project_list:
        if item.star:
            project_dict['star'].append({'value': item.project, 'type': 'join'})
        else:
            project_dict['join'].append(item.project)

    return render(request, "web/project_list.html", {'form': form, 'project_dict': project_dict})

def project_add(request):
    form = ProjectModelForm(request, data=request.POST)
    if form.is_valid():
        name = form.cleaned_data['name']
        # 为项目在云存储中创建一个桶
        bucket = "{}-{}-{}-1316585590".format(name, request.saas.user.mobile_phone, str(int(time.time())))
        region = 'ap-nanjing'
        create_bucket(bucket, region)
        # 将桶和区域写入到数据库

        # 验证通过：项目名、颜色、描述，其他有默认值，需要我们再加一个creator
        # 创建项目
        form.instance.bucket = bucket
        form.instance.region = region
        form.instance.creator = request.saas.user
        form.save()
        return JsonResponse({'status': True})
    return JsonResponse({"status": False, 'error': form.errors})


def project_star(request, project_type, project_id):
    """ 星标项目 """
    if project_type == 'my':
        # 必须加上creator条件，否则可能会更改其他人的项目
        models.Project.objects.filter(id=project_id, creator=request.saas.user).update(star=True)
        # 这样直接重定向效率不高，可以考虑前端发ajax请求
        return redirect('project_list')
    elif project_type == 'join':
        models.ProjectUser.objects.filter(project_id=project_id, user=request.saas.user).update(star=True)
        return redirect('project_list')

    return HttpResponse("请求错误")

def project_unstar(request, project_type, project_id):
    """ 取消星标 """
    """ 星标项目 """
    if project_type == 'my':
        # 必须加上creator条件，否则可能会更改其他人的项目
        models.Project.objects.filter(id=project_id, creator=request.saas.user).update(star=False)
        # 这样直接重定向效率不高，可以考虑前端发ajax请求
        return redirect('project_list')
    elif project_type == 'join':
        models.ProjectUser.objects.filter(project_id=project_id, user=request.saas.user).update(star=False)
        return redirect('project_list')

    return HttpResponse("请求错误")